/*
 * @Author: wangming
 * @Date: 2021-03-30 16:05:05
 * @LastEditors: wangming
 * @LastEditTime: 2022-07-15 16:38:02
 * @Description: file content
 */
import { transformRouter } from '@/utils/common.js'
import { MOS_ENABLED } from '@/utils/const'
import { LayoutRoutes } from '@/router'
import stores from 'store2'
import { getHmusergroupcomponentModelfieldblacklist } from '@/apis/paas/HmUserGroupComponentController.js'
import { getMenupermissionconfigBypage } from '@/apis/paas/HmMenuPermissionConfigController.js'
import vuexStore from '@/store'
const state = {
  menuList: [],
  blackButtons: {},
  blackButtonsPromise: {},
}
const mutations = {
  SET_ROUTES: (state, menuList) => {
    state.menuList = state.menuList.concat(menuList)
  },
  CLEAR_ROUTES: (state) => {
    state.menuList = []
  },
  SET_BLACK_BUTTONS: (state, payload) => {
    const { pageKey, buttons } = payload
    state.blackButtons[pageKey] = buttons
  },
  CLEAR_BLACK_BUTTONS: state => {
    state.blackButtons = {}
  },
  SET_BLACK_BUTTONS_PROMISE: (state, payload) => {
    const { pageKey, promise } = payload
    state.blackButtonsPromise[pageKey] = promise
  },
  CLEAR_BLACK_BUTTONS_PROMISE: state => {
    state.blackButtonsPromise = {}
  }
}

/**
 * 判断应用当前环境
 * @returns 
 */
const getAppEnv = () => {
  let inPortal = stores.get(MOS_ENABLED)
  if (process.env.VUE_APP_USER === 'ADMIN') {
    //设计器
    return 'DESINGER'
  } else if (process.env.VUE_APP_USER === 'APP' && process.env.VUE_APP_ROOT_URL === '/preview') {
    //设计器预览
    return 'PREVIEW'
  } else if (process.env.VUE_APP_USER === 'APP' && process.env.VUE_APP_ROOT_URL === './' && inPortal) {
    //门户部署
    return 'PORTAL'
  } else if (process.env.VUE_APP_USER === 'APP' && process.env.VUE_APP_ROOT_URL === './' && !inPortal) {
    //单应用部署
    return 'STANDALONE'
  } else {
    return 'UNKNOWN'
  }
}

const actions = {
  // TODO 系统内置菜单未使用菜单配置中的信息
  async generateMenus({ commit }, treeList) {
    const env = getAppEnv()
    let menus = transformRouter(treeList, (i) => {
      let envHide = i.meta?.envHide?.split(',') || []
      return i?.meta?.showMenu && !~envHide.indexOf(env)
    })
    // 导出的应用没有市场推送的菜单
    const appInfo = await vuexStore.dispatch("LOAD_APP_INFO")
    if (appInfo.sourceType === 1) {
      menus = transformRouter(menus, (i) => i?.name !== 'appRelease-market')
    }
    commit('SET_ROUTES', menus)
    if (process.env.VUE_APP_USER === 'APP') {
      try {
        await setModelfieldblacklist()
      } catch (error) { }
    }
    // app-开头的在初始化的时候以及添加过了没必要重复添加
    return LayoutRoutes(treeList)
  },

  async loadBlackButtons({ commit, state }, pageKey) {
    if (!pageKey) return
    if (state.blackButtonsPromise[pageKey]) return
    const promise = getMenupermissionconfigBypage({
      pageKey
    })
    commit('SET_BLACK_BUTTONS_PROMISE', {
      pageKey,
      promise
    })
    const res = await promise
    const {
      buttons, superAdmin
    } = res
    commit('SET_BLACK_BUTTONS', {
      pageKey,
      buttons: superAdmin ? [] : buttons
    })
  }

}

/**
 * 字段权限
 */
async function setModelfieldblacklist() {
  const data = await getHmusergroupcomponentModelfieldblacklist()
  const fields = data.filter(i => i?.fieldBlackList?.length > 0)
  stores.session.set('APP_fields', fields)
}
function sortRouter(tree) {
  tree.forEach((node) => {
    if (node.children && node.children.length > 0) {
      node.children = sortRouter(node.children)
    }
  })
  return tree.sort((nodeA, nodeB) => {
    const sA = nodeA?.meta?.serialNum || 999999999
    const sB = nodeB?.meta?.serialNum || 999999999
    return sA - sB
  })
}

const getters = {
  getMenusList({ menuList }, { APP_INFO }) {
    if (process.env.VUE_APP_USER === 'ADMIN') {
      const tree = JSON.parse(JSON.stringify(menuList))
      // 个人应用的设计器 不显示云部署页面
      if (APP_INFO && APP_INFO.tenantId === "JZB1fcFPLhW1WYsyS22Sfg==") {
        let appRelease = tree.find(i => i.name === 'appRelease') || null
        if (appRelease && appRelease.children) {
          let index = appRelease.children.findIndex(i => i.name === "appRelease-cloudDeployment")
          index > -1 && appRelease.children.splice(index, 1)
        }
      }
      const menu = sortRouter(tree)
      return menu
    }
    return menuList
  },
  blackButtons(state) {
    return state.blackButtons
  },
  blackButtonsPromise(state) {
    return state.blackButtonsPromise
  }
}
export default {
  state,
  mutations,
  actions,
  getters
}
